import Mocha from '../../modules/mocha.js';
import RTLog from '../../modules/rt_log.js';
import Util from '../../modules/util.js';
import CheckUserViewResult from '../../modules/count_view_result.js';
import CheckFocusAccount from '../../modules/check_focus_account.js';
import SendMessage from '../../modules/send_message.js';
import FunctionThrottle from '../../modules/function_throttle';
import { formatAgeOrXingZuoData } from '../../modules/format_xingzuo_data';
import { filterNotFocusAccounts } from '../../modules/filter_account';
import { addFriendStatus } from '../../modules/common_methods';

const App = getApp();
let countDownTimer = null;
let rewardedVideoAd = null;
let taskId = null;
let requestFocusCount = 0;
// let defaultAvatar =
//     'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';
let defaultAvatar = 'https://qncdn.mopic.mozigu.net/f/mr6kod18k32ah1s63tg/1263ee2f88f9/syshead.png';

Page({
    data: {
        theme: {},
        info: {}, // 题目列表
        count: 0,
        currentItem: 0,

        showModal: false,
        showCountDown: false,
        countDownTime: 3,
        resultImageUrl: '',
        userAge: null,
        userBirthday: null,
        viewResult: false,
        showAdsVideo: false,
        hiddenResultButton: true,
        accountConfigInfo: null,
        unFocusAccountArray: [],
        accountList: [],
        accountInfo: null,
        progressPercent: 0,

        videoAdId: '',
        rewardedVideoId: '',
        // interstitialadId: '',
        themeColor: getApp().globalData.themeColor,

        customAdStatus: false,
        customAdInfo: {},
        currentCustomItem: {},
        progressValue: 0,
        virtualUserList: [],
        systemInfo: '',

        eventsProcessStatus: true, // 自主广告事件执行状态
        userViewResultCount: -1, // 未关注的公众号数量
        loadingStatus: false,

        customErrorPopup: false,
        errContext: '',

        addFriendStatus: null, // Boolean
        wxworkData: [],
        wxworkQrcode: '',

        userAuthDialog: false
    },
    answers: [],
    mpid: '',
    count: 0,
    linkName: '',
    linkNameArr: [],
    onLoad(options) {
        this.onBeforeunload();
        if (options.scene) {
            const data = decodeURIComponent(options.scene).replace(/'/g, '').split('=');
            this.mpid = data[0] === 'mpid' ? data[1] : options.mpid;
        } else {
            this.mpid = options.mpid;
        }
        this.countPart();
        App.globalData.answers = [];
        wx.showLoading({ title: '加载中...', mask: true });
        wx.getSystemInfo({
            success: (res) => {
                this.setData({
                    systemInfo: res
                });
            }
        });
        this.getMochaQuestions();
        this.getMochaConfig();
        setTimeout(() => {
            getApp().mox.user.openid && this.initGetUserFocusCount();
            getApp().mox.user.unionid && this.isAddWxwork();
        }, 1000);
    },
    getMochaQuestions() {
        Mocha.getProductConfig(this.mpid)
            .then((data) => {
                App.globalData.productInfo = data;
                App.globalData.testTitle = data.h5_config.title || '阔爱大孔农';
                wx.setNavigationBarTitle({
                    title: App.globalData.testTitle
                });
                let productInfo = JSON.parse(JSON.stringify(data));
                productInfo.questions.forEach((item, index) => {
                    item.checker = item.checker || 'radio';
                    if (item.options) {
                        let new_options = [];
                        for (let k in item.options) {
                            new_options.push({
                                key: k,
                                value: item.options[k]
                            });
                        }
                        item.options = new_options;
                    }
                    this.answers[index] = null;
                });

                this.setData({ info: productInfo });
                this.getShareIMageUrl();
            })
            .catch((err) => {
                wx.hideLoading();
                this.setData({
                    errContext: `获取题目列表失败：${err.errMsg || err.msg || '未知错误'}`,
                    customErrorPopup: true
                });
                RTLog.error('getProductConfig fail! err:', err);
            });
    },
    getMochaConfig() {
        Mocha.getConfig()
            .then((cfg) => {
                App.globalData.cfgData = cfg;
                const {
                    wechat_official_account,
                    show_count_down,
                    count_cown_time,
                    advertisements,
                    custom_ad_jump,
                    virtual_user_list,
                    theme
                } = cfg;

                this.setData({
                    wxworkData: cfg?.pageSettings?.result?.verify_identity?.params || [],
                    customAdInfo: {
                        ...custom_ad_jump,
                        count_down_time:
                            custom_ad_jump?.count_down_time > 0 &&
                            custom_ad_jump?.count_down_time <= 4
                                ? 4
                                : custom_ad_jump?.count_down_time
                    },
                    theme,
                    currentCustomItem:
                        custom_ad_jump?.ad_list[
                            parseInt(Math.random() * custom_ad_jump?.ad_list?.length)
                        ],
                    virtualUserList: {
                        isVirtualUser: true,
                        avatarUrl:
                            virtual_user_list[parseInt(Math.random() * virtual_user_list?.length)]
                                ?.avatar,
                        nickName:
                            virtual_user_list[parseInt(Math.random() * virtual_user_list?.length)]
                                ?.nickname
                    }
                });
                wechat_official_account &&
                    this.setData({ accountConfigInfo: wechat_official_account });
                show_count_down && this.setData({ showCountDown: show_count_down });
                count_cown_time && this.setData({ countDownTime: count_cown_time });
                if (advertisements) {
                    const ad = advertisements['pages/testing/testing'];
                    let data = {};
                    if (Array.isArray(ad)) {
                        ad.forEach((item) => {
                            const adType = this.formatAdType(item.ad_type);
                            data[`${adType}Id`] = item.ad_id;
                        });
                        this.setData(data);
                    } else if (ad?.ad_type) {
                        const adType = this.formatAdType(ad.ad_type);
                        data[`${adType}Id`] = ad.ad_id;
                        this.setData(data);
                    }
                    this.onCreateRewardedVideoAd();
                }

                theme.main_color && this.setData({ themeColor: theme.main_color });

                wx.setNavigationBarColor({
                    frontColor: theme.navibar_text_color || '#000000',
                    backgroundColor: '#F5F5F5'
                });
                filterNotFocusAccounts().then((res) => {
                    getApp().globalData.notFocusAccounts = res;
                });
                getApp().mox.stat(`testing page get_mocha_h5_config success`);
            })
            .catch((err) => {
                // getApp().mox.stat(
                //     `testing page get_mocha_h5_config fail：${err.msg || err.errMsg || '未知错误'}`
                // );
                getApp().mox.stat(`testing page get_mocha_h5_config fail`);
                RTLog.error(
                    'testing page get_mocha_h5_config fail：',
                    err.errMsg || err.msg || '未知错误'
                );
                this.setData({
                    errContext: `获取配置项失败：${err.errMsg || err.msg || '未知错误'}`,
                    customErrorPopup: true
                });
            });
    },

    formatAdType(adType) {
        const adTypeKeyArray = adType.split('-');
        adType =
            adTypeKeyArray.length > 1
                ? `${adTypeKeyArray[0]}${adTypeKeyArray[1]
                      .charAt(0)
                      .toLocaleUpperCase()}${adTypeKeyArray[1].slice(1)}`
                : adTypeKeyArray[0];
        return adType;
    },
    onShow() {
        if (!this.data.eventsProcessStatus) {
            this.setData({ eventsProcessStatus: true });
        }
        if (this.data.accountConfigInfo && this.data.accountInfo && !this.data.customAdStatus) {
            if (this.data.systemInfo.platform === 'android') {
                wx.showLoading({
                    title: '加载中...',
                    mask: true
                });
                setTimeout(() => {
                    this.monitorUserFocusAccountStatus();
                }, 1500);
            } else {
                this.monitorUserFocusAccountStatus();
            }
        }
        this.progressValueNotLast();
    },
    // 监测用户关注状态
    monitorUserFocusAccountStatus() {
        const unionid = getApp().mox.user.unionid;
        const appid = this.data.accountInfo.appid;
        CheckFocusAccount.request('GET', `${unionid}?appid=${appid}`)
            .then((res) => {
                if (res[0] && res[0]?.status === 1) {
                    wx.hideHomeButton();
                    getApp().mox.stat(`from_webview_followed`);
                    this.judgeDifferentUrl('page');
                } else {
                    this.setData({ customAdStatus: false, hiddenResultButton: false });
                    clearInterval(this.timer);
                    this.setData({
                        customAdStatus: false
                    });
                    this.onBeforeunload();
                    getApp().mox.stat(`from_webview_no_followed`);
                }
                wx.hideLoading();
                getApp().mox.stat(`check_account_focus success`);
            })
            .catch((err) => {
                wx.hideLoading();
                // getApp().mox.stat(
                //     `check_account_focus fail：${err.msg || err.errMsg || '未知错误'}`
                // );
                getApp().mox.stat(`check_account_focus fail`);
                RTLog.error('check_account_focus fail：', err.errMsg || err.msg || '未知错误');
            });
    },

    isAddWxwork(isFirst = true) {
        if (this.data.wxworkData.length > 0) {
            let url = 'https://api.scf.moapp.net.cn/release/moyu_qywx_contact/api/is_qywx_friend';
            let params = {
                unionid: getApp().mox.user.unionid,
                mpid: 'zhidamp00',
                result_url: isFirst
                    ? '1'
                    : this.data.resultImageUrl != ''
                    ? this.data.resultImageUrl
                    : '1'
            };
            addFriendStatus(url, 'POST', params)
                .then((res) => {
                    if (isFirst) {
                        this.setData({
                            addFriendStatus: res.is_qywx_friend,
                            wxworkQrcode: res.qrcode
                        });
                    }
                    getApp().mox.stat(`testing get_user_add_wxwork_status success`);
                })
                .catch((err) => {
                    getApp().mox.stat(`testing get_user_add_wxwork_status fail`);
                    RTLog.error(
                        'testing get_user_add_wxwork_status fail：',
                        err.errMsg || err.msg || '未知错误'
                    );
                });
        }
    },
    judgeUserJump() {
        clearInterval(this.timer);
        if (this.data.eventsProcessStatus) {
            if (this.data.userViewResultCount >= 2) {
                this.judgeDifferentUrl('page');
            } else {
                if (this.data.accountInfo?.url) {
                    this.judgeDifferentUrl('web');
                } else {
                    this.judgeDifferentUrl('page');
                }
            }
        }
    },
    onBeforeunload() {
        const message = this.data.viewResult ? '看结果' : '答完题';
        wx.enableAlertBeforeUnload({
            message: `还没${message}，确定要离开吗？`
        });
    },
    onCountTime(timestamp) {
        countDownTimer = setInterval(() => {
            this.setData({ count: this.data.count + 1 });
        }, timestamp);
    },
    onQuestionDataChange: FunctionThrottle.throttle(function (evt) {
        const detail = evt.detail;
        // 根据产品配置显示倒计时
        const showCountDownStatus = this.data.showCountDown
            ? detail.index === 0 || this.data.count >= this.data.countDownTime
            : true;
        if (detail.index == this.data.currentItem && showCountDownStatus) {
            // 只处理当前问题的回调
            this.answers[detail.index] = this.formatAnswerValue(detail.value);
            clearInterval(countDownTimer); // 清除上一题的倒计时定时器
            if (this.data.currentItem < this.data.info.questions.length - 1) {
                this.setData({
                    count: 0,
                    currentItem: (this.data.currentItem + 1) % this.data.info.questions.length
                });
                this.onCountTime(1000); // 开始倒计时
            } else {
                clearInterval(countDownTimer);
                this.data.userViewResultCount <= -1 && this.initGetUserFocusCount();
                this.getUserAuth();
            }
        } else {
            wx.showToast({ title: '操作太快啦，请认真读题，稍后再试', icon: 'none' });
        }
    }, 400),

    formatAnswerValue(value) {
        if (value.length === 8) {
            this.setData({
                userBirthday: value.slice(4),
                userAge: new Date().getFullYear() - value.slice(0, 4)
            });
            return value.slice(4);
        } else {
            return value;
        }
    },
    getUserAuth() {
        if (this.data.wxworkQrcode == '') {
            this.isAddWxwork();
        }
        let userInfo = wx.getStorageSync('__session__');
        let parseUserInfo = userInfo ? JSON.parse(userInfo) : {};
        if (
            !parseUserInfo.hasOwnProperty('isVirtualUser') &&
            parseUserInfo.openid &&
            parseUserInfo.unionid &&
            parseUserInfo.nickName &&
            parseUserInfo.nickName != '我' &&
            parseUserInfo.avatarUrl &&
            parseUserInfo.avatarUrl != defaultAvatar
        ) {
            this.onTestingEnd();
        } else {
            if (this.data.systemInfo.platform === 'devtools') {
                wx.showLoading({ title: '登录中...', mask: true });
                wx.getUserProfile({
                    desc: '用于展示信息',
                    success: (resUserInfo) => {
                        wx.hideLoading();
                        let userInfo = resUserInfo.userInfo;
                        getApp().mox.user = {
                            ...getApp().mox.user,
                            avatarUrl: userInfo.avatarUrl
                        };
                        getApp().mox.session._setSessionCache(userInfo);
                        this.onTestingEnd();
                    },
                    fail: (err) => {
                        wx.hideLoading();
                        getApp().mox.stat('user_refuse_auth');
                        RTLog.error('user_refuse_auth：', err.errMsg);
                        getApp().mox.session._setSessionCache(this.data.virtualUserList);
                        this.onTestingEnd();
                    }
                });
            } else {
                this.setData({
                    userAuthDialog: true
                });
            }
        }
    },

    // 点击自主广告
    onTapProduct() {
        App.globalData.answers = this.answers;
        let { type, appid, path, article_link, name = '默认' } = this.data.currentCustomItem;
        this.setData({ eventsProcessStatus: false });
        clearInterval(this.timer);
        if (type == 'article') {
            wx.navigateTo({
                url: '/pages/web/web?accountUrl=' + encodeURIComponent(article_link)
            });
            getApp().mox.stat(`click_custom_ad_article_${name}`);
        } else if (type == 'miniprogram') {
            wx.navigateToMiniProgram({
                appId: appid,
                path,
                success: () => {
                    getApp().mox.stat(`click_custom_ad_miniprogram_${name}`);
                },
                fail: () => {
                    this.setData({ eventsProcessStatus: true });
                    this.progressValueNotLast();
                }
            });
        }
    },
    // 自主广告没到最后
    progressValueNotLast() {
        if (this.data.customAdInfo?.count_down_time && this.data.customAdStatus) {
            if (this.data.progressValue < 100) {
                let speed = (100 * 20) / (this.data.customAdInfo?.count_down_time * 1000);
                this.timer = setInterval(() => {
                    this.setData({
                        progressValue: (this.data.progressValue += speed)
                    });
                    if (this.data.progressValue === 100) {
                        this.judgeUserJump();
                    }
                }, 20);
            }
        }
    },
    // 答题结束后
    onTestingEnd() {
        requestFocusCount += 1;
        App.globalData.answers = this.answers;
        if (!this.data.accountInfo?.url && !this.data.resultImageUrl) {
            this.onIsNeedToFocusAccount();
            this.MakeImageTaskResult();
        }
        if (this.data.userViewResultCount > -1) {
            if (!this.data.customAdInfo?.count_down_time) {
                this.notHasCustomAd();
            } else {
                this.hasCustomAd();
            }
        } else {
            if (requestFocusCount > 4) {
                this.judgeDifferentUrl('web');
                getApp().mox.stat(`testing requestFocusCount > 3`);
                return;
            }
            this.initGetUserFocusCount().then(() => {
                this.onTestingEnd();
            });
        }
    },
    notHasCustomAd() {
        this.setData({ loadingStatus: true });
        if (this.data.videoAdId && this.data.rewardedVideoId) {
            if (this.data.userViewResultCount >= 2) {
                wx.hideHomeButton();
                this.setData({ hiddenResultButton: false, loadingStatus: false });
            } else {
                this.setData({ showModal: true, loadingStatus: false });
            }
        } else {
            this.setData({ loadingStatus: false });
            if (this.linkNameArr.length >= 1 && this.linkName != '') {
                this.disposeTestingEndAfterStatus(false);
            } else {
                this.onTestingEnd();
            }
        }
    },
    hasCustomAd() {
        this.showCustomAd();
        let { name = '默认' } = this.data.currentCustomItem;
        getApp().mox.stat(`custom_ad_${name}_show success`);
        let speed = (100 * 20) / (this.data.customAdInfo?.count_down_time * 1000);
        this.timer = setInterval(() => {
            this.setData({
                progressValue: (this.data.progressValue += speed)
            });
            if (this.data.progressValue === 100) {
                clearInterval(this.timer);
                if (this.linkNameArr.length >= 1 && this.linkName != '') {
                    this.disposeTestingEndAfterStatus();
                } else {
                    this.onTestingEnd();
                }
            }
        }, 20);
    },

    disposeTestingEndAfterStatus() {
        if (this.linkNameArr.length > 1) {
            if (this.linkNameArr[0] == 'wxwork') {
                if (this.data.wxworkData.length > 0 && !this.data.addFriendStatus) {
                    if (this.data.wxworkQrcode != '') {
                        wx.redirectTo({
                            url: `/pages/follow/follow?wxworkqrcode=${this.data.wxworkQrcode}&mpid=${this.mpid}`
                        });
                        this.MakeImageTaskResult(true);
                    } else {
                        this.judgeDifferentUrl('page');
                    }
                } else {
                    if (
                        this.data.userViewResultCount >= 2 ||
                        this.data.unFocusAccountArray.length <= 0
                    ) {
                        this.judgeDifferentUrl('page');
                    } else {
                        this.judgeDifferentUrl('web');
                    }
                }
            } else {
                if (
                    this.data.userViewResultCount >= 2 ||
                    this.data.unFocusAccountArray.length <= 0
                ) {
                    this.judgeDifferentUrl('page');
                } else {
                    this.judgeDifferentUrl('web');
                }
            }
        } else {
            if (this.linkNameArr[0] == 'wxwork') {
                if (this.data.wxworkData.length > 0 && !this.data.addFriendStatus) {
                    if (this.data.wxworkQrcode != '') {
                        wx.redirectTo({
                            url: `/pages/follow/follow?wxworkqrcode=${this.data.wxworkQrcode}&mpid=${this.mpid}`
                        });
                        this.MakeImageTaskResult(true);
                    } else {
                        this.judgeDifferentUrl('page');
                    }
                } else {
                    this.judgeDifferentUrl('page');
                }
            } else {
                if (
                    this.data.userViewResultCount >= 2 ||
                    this.data.unFocusAccountArray.length <= 0
                ) {
                    this.judgeDifferentUrl('page');
                } else {
                    this.judgeDifferentUrl('web');
                }
            }
        }
    },

    judgeDifferentUrl(type) {
        return new Promise((resolve, reject) => {
            if (this.data.eventsProcessStatus) {
                if (type == 'page') {
                    this.onViewAnalyseResult()
                        .then(() => {
                            this.onCancle('noClick');
                        })
                        .catch((err) => {
                            reject(err);
                        });
                } else {
                    !this.data.viewResult && this.setData({ viewResult: true });
                    this.onWebView();
                }
            }
        });
    },
    onIsNeedToFocusAccount() {
        return new Promise((resolve, reject) => {
            const accountConfigInfo = this.data.accountConfigInfo; // 公众号配置信息

            if (accountConfigInfo && accountConfigInfo[this.mpid]) {
                const productInfo = accountConfigInfo[this.mpid];
                const questionIndex = Object.keys(productInfo)[0]; // 对应产品需要关注公众号列表
                const answerIndex = this.answers[questionIndex - 1]; // 答案选项
                const accountList = productInfo[questionIndex]; // 答案选项对应需要关注的公众号列表
                console.log('productInfo', productInfo);
                console.log('questionIndex', questionIndex);
                console.log('this.answers', this.answers);
                console.log('answerIndex', answerIndex);
                console.log('accountList', accountList);
                if (accountList[String(answerIndex)]) {
                    resolve(this.onFocusAccount(accountList[String(answerIndex)]));
                } else {
                    // 根据年龄或星座去分配关注公众号
                    const accountInfo = formatAgeOrXingZuoData(
                        accountList,
                        this.data.userAge,
                        this.data.userBirthday
                    );
                    resolve(this.onFocusAccount(accountInfo));
                }
            } else if (accountConfigInfo && accountConfigInfo['default']) {
                resolve(this.onFocusAccount(accountConfigInfo['default']));
            } else {
                this.judgeDifferentUrl('page');
            }
        });
    },

    onFocusAccount(linkName) {
        let newLinkName = '';
        this.linkName = linkName;
        this.linkNameArr = linkName.split(',');
        newLinkName = this.linkNameArr.filter((item) => item != 'wxwork')[0];
        console.log('6666----------', newLinkName);
        if (
            newLinkName &&
            Object.keys(getApp().globalData.notFocusAccounts).length > 0 &&
            Object.values(getApp().globalData.notFocusAccounts[`${newLinkName}`]).length > 0
        ) {
            this.setData({
                accountList: getApp().globalData.notFocusAccounts[`${newLinkName}`]?.origin,
                unFocusAccountArray: getApp().globalData.notFocusAccounts[`${newLinkName}`]?.after
            });
            this.onRandomFocusAccount(
                getApp().globalData.notFocusAccounts[`${newLinkName}`]?.after
            );
        }
    },

    onRandomFocusAccount(unFocusAccountArray) {
        if (unFocusAccountArray.length <= 0) {
            this.judgeDifferentUrl('page');
            return;
        }
        return new Promise((resolve, reject) => {
            const accountIndex =
                unFocusAccountArray[Math.floor(Math.random() * unFocusAccountArray.length)];

            this.setData({ accountInfo: this.data.accountList[accountIndex] });
            getApp().globalData.accountInfo = this.data.accountInfo;
            const baseUrl = `https://api.ali-fc.moapp.net.cn/check_url`;
            const queryData = {
                url: this.data.accountInfo.url,
                mini_name: '阔爱大孔农',
                appid: this.data.accountInfo.appid
            };

            console.log('----------公众号信息-----------', this.data.accountInfo);

            SendMessage.request(baseUrl, 'POST', queryData)
                .then((res) => {
                    if (res.invalid && !res.appid_invalid) {
                        // 文章链接不可用
                        resolve(this.getAvailableArticleLink());
                    } else {
                        resolve(this.data.accountInfo);
                    }
                    getApp().mox.stat(`check_account_available_status success`);
                })
                .catch((err) => {
                    wx.hideLoading();
                    // getApp().mox.stat(
                    //     `check_account_available_status fail：${
                    //         err.msg || err.errMsg || '未知错误'
                    //     }`
                    // );
                    getApp().mox.stat(`check_account_available_status fail`);
                    RTLog.error(
                        'check_account_available_status fail：',
                        err.errMsg || err.msg || '未知错误'
                    );
                    reject(err);
                });
        });
    },

    getAvailableArticleLink() {
        return new Promise((resolve, reject) => {
            // 文章链接不可用，从未关注公众号列表中删除当前项
            this.data.accountList.forEach((item, index) => {
                if (item.appid == this.data.accountInfo.appid) {
                    this.data.unFocusAccountArray.splice(index, 1);
                }
            });
            try {
                resolve(this.onRandomFocusAccount(this.data.unFocusAccountArray));
            } catch (error) {
                reject(error);
            }
        });
    },

    MakeImageTaskResult(isGetwxworkQrcode = false) {
        return new Promise((resolve, reject) => {
            let answers = this.answers || ['1', '1', '1', '1'];
            answers.unshift(-1);
            Mocha.createMakeImageTask(this.mpid, answers)
                .then((resTaskId) => {
                    taskId = resTaskId;
                    let urlTime = setInterval(() => {
                        Mocha.getMakeImageTaskResult(resTaskId)
                            .then((result) => {
                                if (!result.url) {
                                    getApp().mox.stat(
                                        'testing page get_result_image_url fail：no url'
                                    );
                                    RTLog.error(
                                        'result page get_result_image_url fail：',
                                        'no url'
                                    );
                                } else {
                                    clearInterval(urlTime);
                                    getApp().mox.stat('testing page get_result_image_url success');
                                    this.setData({ resultImageUrl: result.url });
                                    if (isGetwxworkQrcode) {
                                        this.isAddWxwork(false);
                                    }
                                }
                                resolve(this.data.accountInfo);
                                // resolve(this.onSendResultImage(result.url));
                            })
                            .catch((err) => {
                                // getApp().mox.stat(
                                //     `testing page get_result_image_url fail:${
                                //         err.errMsg || err.msg || '未知错误'
                                //     }`
                                // );
                                if ((err.errMsg || err.msg) == '查询出错') return;
                                getApp().mox.stat(`testing page get_result_image_url fail`);
                                RTLog.error(
                                    'testing page get_result_image_url fail：',
                                    err.errMsg || err.msg || '未知错误'
                                );
                                reject(err);
                            });
                    }, 800);
                    getApp().mox.stat('testing page make_task success');
                })
                .catch((err) => {
                    // getApp().mox.stat(
                    //     `testing page make_task fail:${err.errMsg || err.msg || '未知错误'}`
                    // );
                    getApp().mox.stat(`testing page make_task fail`);
                    RTLog.error(
                        'testing page make_task fail：',
                        err.errMsg || err.msg || '未知错误'
                    );
                    reject(err);
                });
        });
    },

    onWebView() {
        let url = Util.formatUrl(this.data.accountInfo?.url);
        wx.navigateTo({
            url: `/pages/web/web?accountUrl=${url}&mpid=${this.mpid}&resultUrl=${this.data.resultImageUrl}&taskId=${taskId}`,
            complete: () => {
                this.setData({ customAdStatus: false });
            }
        });
        wx.hideLoading();
    },

    onCancle: FunctionThrottle.throttle(function (status) {
        this.count = 6;
        if (status == 'noClick') {
            getApp().mox.stat(`noClick_look_result_button`);
            // this.onWebView();
        } else {
            getApp().mox.stat(`click_look_result_button`);
        }
        wx.redirectTo({
            url: `/pages/result/result?mpid=${this.mpid}&url=${this.data.resultImageUrl}`
        });
        this.setData({ customAdStatus: false });
    }, 1500),

    showVideoAds(timeStamp) {
        let videoTimer = setInterval(() => {
            if (this.data.progressPercent === 100) {
                clearInterval(videoTimer);
                this.judgeDifferentUrl('page');
            } else {
                this.setData({ progressPercent: this.data.progressPercent + 1 });
            }
        }, timeStamp);
        this.setData({ showModal: false, showAdsVideo: true });
    },

    onConfirm() {
        this.setData({ showModal: false });
        if (this.data.accountConfigInfo) {
            this.judgeDifferentUrl('page');
        } else {
            rewardedVideoAd.show().catch(() => {
                rewardedVideoAd
                    .load()
                    .then(() => rewardedVideoAd.show())
                    .catch(() => {
                        console.log('激励视频 广告显示失败');
                    });
            });
        }
    },

    initGetUserFocusCount() {
        return new Promise((resolve, reject) => {
            CheckUserViewResult.request()
                .then((res) => {
                    if (res.key && res.key != 'null') {
                        this.setData({
                            userViewResultCount: res.count
                        });
                        resolve(this.data.userViewResultCount);
                        getApp().mox.stat(`init get_user_focus_count success`);
                    }
                })
                .catch((err) => {
                    // getApp().mox.stat(
                    //     `init get_user_focus_count fail:${err.errMsg || err.msg || '未知错误'}`
                    // );
                    getApp().mox.stat(`init get_user_focus_count fail`);
                    RTLog.error(
                        'init get_user_focus_count fail：',
                        err.errMsg || err.msg || '未知错误'
                    );
                    reject(err);
                });
        });
    },
    onCreateRewardedVideoAd() {
        if (wx.createRewardedVideoAd) {
            rewardedVideoAd = wx.createRewardedVideoAd({
                adUnitId: this.data.rewardedVideoId
            });
            rewardedVideoAd.onLoad(() => {
                console.log('onLoad ');
            });
            rewardedVideoAd.onError((err) => {
                console.log('onError', err);
            });
            rewardedVideoAd.onClose((res) => {
                if (res && res.isEnded) {
                    // 正常播放结束，可以下发游戏奖励
                    this.setData({ hiddenResultButton: true });
                    this.judgeDifferentUrl('page');
                } else {
                    this.setData({ showModal: false });
                    wx.hideHomeButton();
                    this.setData({ hiddenResultButton: false });
                }
            });
        }
    },

    onViewAnalyseResult() {
        return new Promise((resolve, reject) => {
            try {
                App.globalData.answers = this.answers;
                if ((this.data.videoAdId && this.data.rewardedVideoId) || this.data.accountInfo) {
                    CheckUserViewResult.request('POST').catch((err) => {
                        wx.hideLoading();
                        // getApp().mox.stat(
                        //     `testing page add_count_view_result fail:${
                        //         err.errMsg || err.msg || '未知错误'
                        //     }`
                        // );
                        getApp().mox.stat(`testing page add_count_view_result fail`);
                        RTLog.error(
                            'testing page add_count_view_result fail：',
                            err.errMsg || err.msg || '未知错误'
                        );
                    });
                }
                resolve(this.answers);
            } catch (error) {
                reject(error);
            }
        });
    },

    showCustomAd() {
        this.setData({
            customAdStatus: true
        });
    },
    onHide() {
        clearInterval(this.timer);
        this.setData({
            eventsProcessStatus: false
        });
    },
    onUnload() {
        clearInterval(this.timer);
        this.setData({
            customAdStatus: false,
            progressValue: 0,
            eventsProcessStatus: false
        });
    },
    openResultButton() {
        this.setData({
            hiddenResultButton: false
        });
    },
    closeUserAuthDialog() {
        wx.setStorage({
            key: '__session__',
            data: JSON.stringify({
                ...getApp().mox.user,
                ...this.data.virtualUserList
            })
        });
        this.setData(
            {
                userAuthDialog: false
            },
            () => {
                this.onTestingEnd();
            }
        );
    },
    confirmUserAuthDialog() {
        this.setData(
            {
                userAuthDialog: false
            },
            () => {
                this.onTestingEnd();
            }
        );
    },
    getShareIMageUrl() {
        Mocha.getProductList()
            .then((res) => {
                wx.hideLoading();
                res.forEach((item) => {
                    if (item.mpid === this.mpid) {
                        App.globalData.shareImageUrl = item.thumb;
                    }
                });
                getApp().mox.stat(`testing page get_mocha_product success`);
            })
            .catch((err) => {
                wx.hideLoading();
                // getApp().mox.stat(
                //     `testing page get_mocha_product fail:${err.errMsg || err.msg || '未知错误'}`
                // );
                getApp().mox.stat(`testing page get_mocha_product fail`);
                RTLog.error(
                    'testing page get_mocha_product fail：',
                    err.errMsg || err.msg || '未知错误'
                );
            });
    },
    countPart() {
        let pages = getCurrentPages();
        let currentPage = pages[pages.length - 2];
        if (!currentPage?.route && !currentPage?.route.includes('pages/index/index')) {
            getApp().mox.stat('testing|all');
            getApp().mox.stat('testing|' + this.mpid.slice(-2));
        }
    }
});
